<?php
/**
 *
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/15
 * Time: 23:26
 */

namespace app\lib\exception;
use think\Exception;
use think\exception\Handle;
use think\Log;
use think\Request;


class ExceptionHandler extends Handle
{
    public $code;
    public $msg;
    public $errorCode;

    public function render(\Exception $e)
    {
        if ($e instanceof BaseException) {
            //定义行为异常
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        } else {
            //定义一个开关
            $switch = config('app_debug');
            if($switch) {
               return parent::render($e);
            }else {
                //定义服务器异常
                $this->code = 500;
                $this->msg = '服务器异常';
                $this->errorCode = 10000;
                $this->recordError($e);
            }

        }
        $request = Request::instance();
        $result = [
            'msg' => $this->msg,
            'code' => $this->code,
            'request_url' => $request->url(),
            'errorCode' => $this->errorCode
        ];
        return json($result, $this->code);
    }

    //错误日志的方法
    public function recordError(\Exception $e)
    {
        Log::init([
            'type' => 'File',
            'path' => LOG_PATH,
            'level' => ['error'],
        ]);
        Log::record($e -> getMessage(), 'error');
    }
}